﻿using System;
using System.Net;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using System.Windows.Forms;
using Outlook = Microsoft.Office.Interop.Outlook;
using Excel = Microsoft.Office.Interop.Excel;
using Office = Microsoft.Office.Core;
using System.IO;
using System.Security.Cryptography;
using System.Runtime.Serialization.Json;
using System.Threading;

namespace TNCAddIn
{
    public partial class ThisAddIn
    {
        private Office.CommandBar tncBar;
        private Office.CommandBarPopup tncMenu;
        private Office.CommandBarButton sendBtn, passwdBtn, aboutBtn, defBcBtn;
        private string menuTag = "tncmenu";
        private string currentUserName;
        private string currentUserAddress;
        private Thread syncThread;

        private void ThisAddIn_Startup(object sender, System.EventArgs e)
        {
            RemoveTNCBar();
            AddTNCBar();
            
            //验证临时文件夹
            if (Directory.Exists(Properties.Settings.Default.TempDir) == false)//如果不存在就创建file文件夹
            {
                Directory.CreateDirectory(Properties.Settings.Default.TempDir);
            }
            
            Outlook.AddressEntry addrEntry = Application.Session.CurrentUser.AddressEntry;
            
            currentUserAddress = Application.Session.CurrentUser.Address;
            currentUserName = Application.Session.CurrentUser.Name;
            if (addrEntry.Type == "EX") {
                currentUserAddress = Application.Session.CurrentUser.AddressEntry.GetExchangeUser().PrimarySmtpAddress;
            }

            //MessageBox.Show("Hello, " + currentUserName + "," + currentUserAddress);
            
            if (Properties.Settings.Default.Key.Length != 32
                || Properties.Settings.Default.DefaultBudgetCenter == null
                || Properties.Settings.Default.DefaultBudgetCenter == "") {
                passwordDialog();
            }

            Outlook.MAPIFolder defaultCalendar = Application.Session.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderCalendar);

            Outlook.Items appointments = Application.Session.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderCalendar).Items;

            Outlook.MAPIFolder calendar = Application.Session.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderCalendar);

            appointments.ItemAdd += new Outlook.ItemsEvents_ItemAddEventHandler(appointments_ItemAdd);

            Object item = appointments.GetNext();
            while (item != null) {

                Outlook.AppointmentItem appointment = item as Outlook.AppointmentItem;
                if (appointment != null)
                {
                    appointment.BeforeDelete += new Outlook.ItemEvents_10_BeforeDeleteEventHandler(item_BeforeDelete);
                    item_PropertyChange(appointment);
                }
                item = appointments.GetNext();
            }

            /*foreach(Outlook.AppointmentItem item in appointments) {
                item.BeforeDelete += new Outlook.ItemEvents_10_BeforeDeleteEventHandler(item_BeforeDelete);
                item_PropertyChange(item);
            }*/

            Sync sync = new Sync();
            sync.Mail = currentUserAddress;
            sync.Items = appointments;
            syncThread = new Thread(sync.SyncWorker);
            syncThread.Start();

            // What we are trying to do here, is to obtain the email address and the display name of the current outlook user.
            // 获取当前exchange用户
            /*if (addrEntry.Type == "EX")
            {
                currentUser = Application.Session.CurrentUser.AddressEntry.GetExchangeUser();
                //验证密码是否存在
                if (Properties.Settings.Default.Key.Length != 32)
                {
                    Password pass = new Password();
                    pass.Show();
                }
                //获取全部约会
                Outlook.Items appt = Application.Session.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderCalendar).Items;
                Sync sync = new Sync();
                sync.Mail = currentUser.PrimarySmtpAddress;
                sync.Items = appt;
                //开启线程进行同步
                syncThread = new Thread(sync.SyncWorker);
                syncThread.Start();
            }
            else if (addrEntry.Type == "SMTP") {
                MessageBox.Show("未连接到Exchange服务器!" + Application.Session.CurrentUser.Address);
            }*/
        }

        void appointments_ItemAdd(object Item)
        {
            ((Outlook.AppointmentItem)Item).BeforeDelete += new Outlook.ItemEvents_10_BeforeDeleteEventHandler(item_BeforeDelete);
            item_PropertyChange((Outlook.AppointmentItem)Item);
        }
        
        void item_PropertyChange(Outlook.AppointmentItem item) { 
            item.PropertyChange+=new Outlook.ItemEvents_10_PropertyChangeEventHandler(delegate(string name) {
                if (item.UserProperties["sync"] == null)
                    item.UserProperties.Add("sync", Outlook.OlUserPropertyType.olText);
                item.UserProperties["sync"].Value = "no";
            });
        }

        void item_BeforeDelete(object Item, ref bool Cancel)
        {
            try
            {
                lock (Properties.Settings.Default.List)
                {
                    Outlook.AppointmentItem item = (Outlook.AppointmentItem)Item;
                    if (Properties.Settings.Default.List.IndexOf(item.GlobalAppointmentID) != -1)
                    {
                        return;
                    }
                    if (Properties.Settings.Default.List != "")
                        Properties.Settings.Default.List += ",";
                    Properties.Settings.Default.List += item.GlobalAppointmentID;
                    Properties.Settings.Default.Save();
                }
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }
        }

        //插入TNC菜单
        private void AddTNCBar()
        {
            try
            {
                tncBar = this.Application.ActiveExplorer().CommandBars.ActiveMenuBar;
                tncMenu = (Office.CommandBarPopup)tncBar.Controls.Add(
                    Office.MsoControlType.msoControlPopup, missing,
                    missing, missing, false);
                if (tncMenu != null)
                {
                    tncMenu.Caption = "TNC菜单";
                    tncMenu.Tag = menuTag;
                                   
                    aboutBtn = (Office.CommandBarButton)tncMenu.Controls.
                    Add(Office.MsoControlType.msoControlButton, missing,
                        missing, 1, true);
                    aboutBtn.Style = Office.MsoButtonStyle.
                        msoButtonIconAndCaption;
                    aboutBtn.Caption = "关于TNC插件";
                    aboutBtn.FaceId = 65;
                    aboutBtn.Tag = "关于TNC插件";
                    //aboutBtn.Picture = getImage(Properties.Resources.IconAbout);
                    aboutBtn.Click += new
                        Office._CommandBarButtonEvents_ClickEventHandler(
                        aboutBtn_Click);
                    aboutBtn.BeginGroup = true;

                    passwdBtn = (Office.CommandBarButton)tncMenu.Controls.
                    Add(Office.MsoControlType.msoControlButton, missing,
                        missing, 1, true);
                    passwdBtn.Style = Office.MsoButtonStyle.
                        msoButtonIconAndCaption;
                    passwdBtn.Caption = "输入个人密码";
                    passwdBtn.FaceId = 65;
                    passwdBtn.Tag = "输入个人密码";
                    passwdBtn.Click += new
                        Office._CommandBarButtonEvents_ClickEventHandler(
                        passwdBtn_Click);
                    
                    sendBtn = (Office.CommandBarButton)tncMenu.Controls.
                    Add(Office.MsoControlType.msoControlButton, missing,
                        missing, 1, true);
                    sendBtn.Style = Office.MsoButtonStyle.
                        msoButtonIconAndCaption;
                    sendBtn.Caption = "发送工作情况";
                    sendBtn.FaceId = 65;
                    sendBtn.Tag = "发送个人工作情况";
                    sendBtn.Click += new
                        Office._CommandBarButtonEvents_ClickEventHandler(
                        sendBtn_Click);

                    defBcBtn = (Office.CommandBarButton)tncMenu.Controls.Add(Office.MsoControlType.msoControlButton, missing, missing, 1, true);
                    defBcBtn.Style = Office.MsoButtonStyle.msoButtonIconAndCaption;
                    defBcBtn.Caption = "设置默认预算中心";
                    defBcBtn.FaceId = 65;
                    defBcBtn.Tag = "设置默认预算中心";
                    defBcBtn.Click += new Office._CommandBarButtonEvents_ClickEventHandler(defBcBtn_Click);


                    tncMenu.Visible = true;
                }
            }
            catch (Exception ex)
            {
                //MessageBox.Show(ex.Message);
            }
        }

        private void defBcBtn_Click(Office.CommandBarButton ctrl, ref bool cancel) {
            DefaultBudgetCenter dbc = new DefaultBudgetCenter();
            dbc.ShowDialog();
        }

        //点击发送按钮，选择月份，获取该月份的表格，发送邮件
        private void sendBtn_Click(Office.CommandBarButton ctrl,
            ref bool cancel)
        {
            //显示选择月份窗口
            SelectMonthForm smf = new SelectMonthForm();
            smf.ShowDialog();
            
            if (smf.DialogResult == DialogResult.OK)
            {
                DateTime dt = Convert.ToDateTime(smf.Month);
                String att = Properties.Settings.Default.TempDir + this.currentUserName + dt.ToString(" yyyy年MM月") + @"工作情况.xlsx";

                try
                {
                    //下载统计数据表格
                    HttpClient hc = new HttpClient();
                    hc.AuthDownload(currentUserAddress, smf.Month + "," + DateTime.Now.ToString(), att, true);
                    //邮件发送表格
                    Outlook.MailItem mail = Application.CreateItem(Outlook.OlItemType.olMailItem) as Outlook.MailItem;
                    mail.Subject = this.currentUserName + dt.ToString(" yyyy年MM月") + "工作情况";
                    mail.Body = "您好！\n    附件是我" + dt.ToString("yyyy年MM月") + "的工作情况，请查收，谢谢！";
                    mail.Attachments.Add(att, Outlook.OlAttachmentType.olByValue, Type.Missing, Type.Missing);
                    mail.Display(true);
                }
                catch (Exception e) 
                {
                    //MessageBox.Show(e.Message);
                }
            }
        }

        private void passwordDialog() {
            Password password = new Password();
            password.Show();
        }

        //输入密码
        private void passwdBtn_Click(Office.CommandBarButton ctrl,
           ref bool cancel)
        {
            passwordDialog();
        }

        //关于TNC
        private void aboutBtn_Click(Office.CommandBarButton ctrl,
            ref bool cancel)
        {
            AboutTNCAddIn tncAbout = new AboutTNCAddIn();
            tncAbout.ShowDialog();
        }

        //删除工具栏
        private void RemoveTNCBar()
        {
            // If the menu already exists, remove it.
            try
            {
                Office.CommandBarPopup foundMenu = (Office.CommandBarPopup)
                    this.Application.ActiveExplorer().CommandBars.ActiveMenuBar.
                    FindControl(Office.MsoControlType.msoControlPopup,
                    missing, menuTag, true, true);
                if (foundMenu != null)
                {
                    foundMenu.Delete(true);
                }
            }
            catch (Exception ex)
            {
//                MessageBox.Show(ex.Message);//
            }
        }

        private void ThisAddIn_Shutdown(object sender, System.EventArgs e)
        {
            if (syncThread != null)
                syncThread.Abort();
            //RemoveTNCBar();
        }

        #region VSTO generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InternalStartup()
        {
            this.Startup += new System.EventHandler(ThisAddIn_Startup);
            this.Shutdown += new System.EventHandler(ThisAddIn_Shutdown);
        }
        
        #endregion
    }
}
